<?php
if(isset($_GET['install']))
{
	$dbsql->query("DROP PROCEDURE IF EXISTS `UpdateOnline`;");
	$dbsql->query("
CREATE  PROCEDURE `UpdateOnline`(in IP varchar(20),in URL varchar(200),in LANG varchar(5))
begin
	DECLARE countrow int(4);
	DECLARE timenow int(9);
	DECLARE datenow varchar(50);
	SET  time_zone = 'Asia/Bangkok';
	set datenow=now();
	set timenow=UNIX_TIMESTAMP(datenow);

	delete from tblonline where iTime<(timenow-60*60);
	select count(cIP) as url from tblonline where cIp=IP and iTime>(timenow-60*60*24) into countrow;

	if countrow =0 then
		insert into tblonline(cIp,iTime,cUrlEnd,cLanguage,dTimeBegin,iCountPage)
		values(IP,timenow,URL,LANG,datenow,1);
		
		update tblconfig set cValue='0',cType=datenow where cName='ratetoday' and cType!=datenow;
		update tblconfig set cValue='0',cType=WEEK(datenow) where cName='rateweek' and cType!=WEEK(datenow);
		update tblconfig set cValue='0',cType=MONTH(datenow) where cName='ratemonth' and cType!=MONTH(datenow);
		update tblconfig set cValue='0',cType=YEAR(datenow) where cName='rateyear' and cType!=YEAR(datenow);
		update tblconfig set cValue=cValue+1 where cName='ratetoday' or cName='rateweek' or cName='ratemonth'
					or cName='rateyear' or cName='ratesite';
	else
		update tblonline set
				iTime=timenow,
				cUrlEnd=URL,
				iCountPage=iCountPage+1
			where cIp=IP and iTime> (timenow-60*60*24)  limit 1;
	end if;

end;");
}
$rates=LoadRate();
$online=CountOnlineNow();

function LoadRate()
{
global $language,$dbsql;
	  $rates=array();
	  $arr=array("ratetoday","rateweek","ratemonth","rateyear","ratesite");
	  $sql_select = "select cName,cValue from tblconfig where cName like 'rate%'";      
      $rs=$dbsql->query($sql_select);
      $rows = $dbsql->num_rows($rs);
      if($rows==0)
      {
      	foreach ($arr as $i=>$key)
      	{
      		$sql_insert="insert into tblconfig(cName,cType,cValue) values('$key','0','0')";
      		$dbsql->query($sql_insert);
      	}
      }
	  while($result = $dbsql->fetch_array($rs))
	  {
	  		$rates[$result['cName']]=$result;
	  }
	  return $rates;
}
function CountOnlineNow()
{
global $language,$dbsql;
	  $timeold=time()-(60*50);
	  
	  $sql_select = "select count(cIp) as count from tblonline  where iTime>$timeold and iCountPage>0";      
      $rs=$dbsql->query($sql_select);
      $result = $dbsql->fetch_array($rs);
	  return $result["count"];
}


?>